export default {
    name: 'DepartmentList',
    components: {
        DepartmentForm: () => import('../../components/DepartmentForm.vue')
    },
    data() {
        return {
            searchForm: {
                departmentName: '',
                departmentCode: ''
            },
            tableData: [],
            loading: false,
            pagination: {
                current: 1,
                size: 10,
                total: 0
            },
            dialogVisible: false,
            dialogTitle: '',
            currentDepartment: {
                departmentId: null,
                departmentCode: '',
                departmentName: '',
                departmentStaffNumber: 0,
                departmentHistoryStaffNumber: 0,
                remarks: ''
            }
        }
    },
    created() {
        this.fetchDepartmentList();
    },
    methods: {
        fetchDepartmentList() {
            // 这里实现获取部门列表数据的逻辑
            this.loading = true;
            // 模拟API调用
            setTimeout(() => {
                this.tableData = [
                    {
                        departmentId: 1,
                        departmentCode: 'DEPT001',
                        departmentName: '研发部',
                        departmentStaffNumber: 20,
                        departmentHistoryStaffNumber: 50,
                        remarks: '技术研发中心'
                    },
                    {
                        departmentId: 2,
                        departmentCode: 'DEPT002',
                        departmentName: '市场部',
                        departmentStaffNumber: 15,
                        departmentHistoryStaffNumber: 30,
                        remarks: '市场推广部门'
                    }
                ];
                this.pagination.total = 2;
                this.loading = false;
            }, 500);
        },
        handleSearch() {
            this.pagination.current = 1;
            this.fetchDepartmentList();
        },
        resetSearch() {
            this.searchForm.departmentName = '';
            this.searchForm.departmentCode = '';
            this.handleSearch();
        },
        handleSizeChange(size) {
            this.pagination.size = size;
            this.fetchDepartmentList();
        },
        handleCurrentChange(current) {
            this.pagination.current = current;
            this.fetchDepartmentList();
        },
        handleSortChange({ prop, order }) {
            // 这里实现排序逻辑
            console.log('排序字段:', prop, '顺序:', order);
            this.fetchDepartmentList();
        },
        handleCreate() {
            this.$router.replace({ path: '/employee/AddDepartment' });
        },
        handleEdit(row) {
            this.dialogTitle = '编辑部门';
            this.currentDepartment = { ...row };
            this.dialogVisible = true;
        },
        handleDelete(row) {
            this.$confirm(`确定要删除部门【${row.departmentName}】吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 这里实现删除逻辑
                this.$message.success('删除成功');
                this.fetchDepartmentList();
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        handleSubmit(formData) {
            // 这里实现提交逻辑
            console.log('提交数据:', formData);
            this.$message.success('操作成功');
            this.dialogVisible = false;
            this.fetchDepartmentList();
        },
        exportDepartmentList() {
            try {
                this.loading = true;

                // 1. 准备CSV内容（添加BOM头解决中文乱码）
                let csvContent = "\uFEFF"; // UTF-8 BOM头

                // 2. 添加中文表头
                csvContent += "部门ID,部门编号,部门名称,当前人数,历史人数,备注\n";

                // 3. 添加数据行
                this.tableData.forEach(dept => {
                    csvContent += [
                        dept.departmentId,
                        `"${dept.departmentCode}"`,       // 用引号包裹，避免内容中有逗号导致错位
                        `"${dept.departmentName}"`,
                        dept.departmentStaffNumber,
                        dept.departmentHistoryStaffNumber,
                        `"${dept.remarks || ''}"`         // 处理可能的undefined/null值
                    ].join(',') + '\n';
                });

                // 4. 创建Blob对象（指定UTF-8编码）
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

                // 5. 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.href = url;

                // 6. 设置文件名（使用当前日期）
                const now = new Date();
                const dateStr = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
                link.setAttribute('download', `部门列表_${dateStr}.csv`);

                // 7. 触发下载
                document.body.appendChild(link);
                link.click();

                // 8. 清理DOM和内存
                setTimeout(() => {
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url);
                    this.$message.success('部门数据导出成功');
                }, 100);

            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error(`导出失败: ${error.message}`);
            } finally {
                this.loading = false;
            }
        }
    }
}